package string;

import java.util.Stack;
import java.util.StringTokenizer;

public class PolishNotation {
    public static void main(String[] args) {
        String expression = "java isnumber1 + 2 + 3 * 5";
        doShutingYardAlgo(expression); // Infix --> Postfix
    }

    private static void doShutingYardAlgo(String expression) {
        StringTokenizer stringTokenizer = new StringTokenizer(expression);
        Stack<String> stack = new Stack<String>();
        while (stringTokenizer.hasMoreTokens()) {
            final String token = stringTokenizer.nextToken();
            if (isNumber(token)) { // Operand
                System.out.print(token + " ");
            } else { // Operator
                while (!stack.isEmpty()) {
                    final String stackTop = stack.peek();
                    if (operatorPriorityIsHigherOrEqual(stackTop, token)) {
                        System.out.print(stack.pop() + " ");
                    } else {
                        break;
                    }
                }
                stack.push(token);
            }
        }
        while (!stack.isEmpty()) {
            System.out.print(stack.pop() + " ");
        }
    }

    private static boolean operatorPriorityIsHigherOrEqual(String stackTop, String token) {
        if ((stackTop.equals("+") || stackTop.equals("-")) && (token.equals("*") || token.equals("\\"))) {
            return false;
        }
        return true;
    }

    private static boolean isNumber(String token) {
        for (char c : token.toCharArray()) {
            if (!Character.isDigit(c)) {
                return false;
            }
        }
        return true;
    }
}
